import json

import scrapy
from mashangpa.responce_parse.parserFactory import ParserFactory
from scrapy.http import Request, Response

class MashangpaReverseSpider(scrapy.Spider):
    name = "mashangpa"
    allowed_domains = ["mashangpa.com"]
    base_url = "https://mashangpa.com/api/problem-detail/"
    # start_urls = ["https://mashangpa.com/problem-detail/1/"]
    start_urls = []
    start_url = ""
    parser = None
    question = None
    total_sum = 0

    def __init__(self, question = 1, **kwargs):
        super().__init__(**kwargs)

        question = int(question)
        if question < 1 or question > 20:
            raise ValueError("question must be between 1 and 20")
        self.question = question
        self.start_url = self.base_url + str(question) + "/"

        self.parser = ParserFactory.get_parser(question)
        self.total_sum = 0

    async def start(self):

        request_url = self.start_url + "data/?"
        for i in range(20):
            param = self.parser.encryption_param(i + 1)
            yield Request(url=request_url,method=self.parser.method, callback=self.parse, body=json.dumps(param), dont_filter=True)

    def parse(self, response):
        json = response.json()
        yield json

    def accumulate(self, num: int):
        self.total_sum += num


    def closed(self, response):
        print(f"所有一维列表的最终合计：{self.total_sum}")


if __name__ == '__main__':
    pass